import axios from 'axios';
// import router from '../axios/index';

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';

const myAxios = axios.create({
  baseURL: 'http://127.0.0.1',
  timeout: 10000,
});

// 请求拦截器
myAxios.interceptors.request.use((config) => {
  // 获取token等
  const token = window.localStorage.getItem('token');
  // eslint-disable-next-line no-param-reassign
  if (token) config.headers.authorization = token;
  return config;
}, (error) => {
  Promise.reject(error);
});

// 响应拦截器
myAxios.interceptors.response.use((res) => {
  // 未设置状态码，则默认成功0
  const code = res.data.code || 0;
  switch (code) {
    case 0:
      if (res.data && res.data.token) window.localStorage.setItem('token', res.data.token);
      return res.data;
    case 401:
      window.localStorage.removeItem('token');
      console.log('401');
      // return router.replace({
      //   path: '/chartLogin',
      // });
      return Promise.reject('请登录');
    default:
      return Promise.reject(`请求异常(${res.data})`);
  }
});

export default myAxios;
